#include "RenzoDynLibManager.h"
#include "RenzoDynlib.h"

namespace Renzo {
DynLibManager* DynLibManager::dynLibManager = 0;
DynLibManager* DynLibManager::instance() {
	if (dynLibManager == 0)
		dynLibManager = new DynLibManager;

	return dynLibManager;
}

DynLibManager::DynLibManager(void)
{
	
}

DynLibManager::~DynLibManager(void)
{
	// empty the libs array
	for (DynLibList::iterator i = libs.begin(); i != libs.end(); i++) {
		//this->unload(i->second); // no need to search again
		i->second->unload();
		delete i->second;
	}
	libs.clear();

	// delete singleton
	if (dynLibManager != 0)
		delete dynLibManager;
}

DynLib* DynLibManager::load(const char* dll) {
	DynLibList::iterator i = libs.find(dll);
	if (i != libs.end()) { // this dll is already loaded 
		return i->second;
	} else {
		DynLib* d = new DynLib(dll);
		d->load();
		libs[dll] = d;
		return d;
	}
}

void DynLibManager::unload(DynLib* dll) {
	DynLibList::iterator i = libs.find(dll->getName());
	if (i != libs.end()) { // this dll is loaded and it is safe to unload
		libs.erase(i);
	}
	dll->unload();
	delete dll;
}
}
